<?php

header('Content-type: text/html; charset=utf-8');
ob_start(); //Begin traking data
//Param parser
#remove the directory path we don't want 
$url = $_SERVER['REQUEST_URI'];
$url = ltrim($url, '/');
$request = $url;
$host = "/bret";
$bret = '';
$absoluteUrl = 'http://' . $_SERVER['HTTP_HOST'] . $host;
$request = substr($request, strlen($host));
if (strpos($request, '?') != '') {
    $request = substr($request, 0, strpos($request, "?"));
}
#split the path by '/'
$params = explode("/", $request);

session_start();
$userId = '';
if (isset($_SESSION['bret_userid']))
    $userId = $_SESSION['bret_userid'];
$userId = 1;

session_write_close();
//detect device
include("Libs/mobiledetect/Mobile_Detect.php");
$detect = new Mobile_Detect;
$deviceType = ($detect->isMobile() ? ($detect->isTablet() ? 'Tablet' : 'Mobile') : 'Desktop');

//Load all php file
include("ClassLoader/Loader.php");
$loader = new Loader();
$loader->load();

$curUser = User::withId($userId);
$pageTitle = "";

if (!$userId && strtoupper($params[0]) != "M" && strtoupper($params[0]) != "WS" && strtoupper($params[0]) != "AJAX")
    $params[0] = 'LOGIN';
switch (strtoupper($params[0])) {
    case "USER":
        if (strtoupper($params[0]) == 'LOGIN')
            $params[0] = "USERLOGIN";
        $pageTitle = "Login to buzzPulse";
        break;
    case "M":
        //$soapRequest = $_REQUEST['request'];
        $server = new bpServer("/m/");

        $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
        $server->service($HTTP_RAW_POST_DATA);
        return;
        break;
    case "":
        $params[0] = "HOME";
    case "HOME":
        $pageTitle = "Welcome to The Bret";
        break;
    case "EXPLORE":
        $pageTitle = "Explore The Bret";
        break;
    case "BRET":
        $pageTitle = "Your Bret";
        break;
    case "MANAGER":
        $pageTitle = "Manager The Bret";
        $managerController = new ManagerController(new stdClass(), new stdClass());
        $managerController->render();
        break;
    case "LOGIN":
        $userView = UserView::getInstance();
        $userView->display("LoginViewHTML.php");
        $pageTitle = "Login to Bret";
        break;
    case "LOGOUT":
        $userId = null;
        session_start();
        $_SESSION['bret_userid'] = null;
        session_write_close();
        echo "<script>window.location = '{$host}'</script>";
        break;
    case "EDIT":
        $bretId = 0;
        if (isset($params[1]))
            $bretId = $params[1];
        unset($params[1]);
        $pageTitle = "Bret editor";
        $bret = Bret::withId($bretId);
        break;
    case "TEST":
        break;
    case "AJAX":
        switch (strtoupper($params[1])) {
            case "NEWUSER":
                include "View/".$deviceType."/Ajax/NewUserHTML.php";
                break;
            case "REGISTER":
                include "View/".$deviceType."/Ajax/RegisterHTML.php";
                break;
            default:
                break;
        }
        return;
    case "WS":
        switch (strtoupper($params[1])) {
            case "TEST":
                $db = Database::getInstance();
                $connectionId = $_GET['connectionId'];
                $clientId = $_GET['clientId'];
                $latency = $_GET['latency'];

                $query = "INSERT INTO `test` (connectionid, clientid, latency) VALUES ($connectionId, $clientId, $latency)";
                $db->query($query);
                exit();
                break;
            case "LOGIN":
                if (!isset($_POST['email']))
                    die('no data');
                $loginInfo['email'] = $_POST['email'];
                $loginInfo['password'] = $_POST['password'];
                $result = User::login($loginInfo);
                echo json_encode($result);
                break;
            case "BRETS":
                $result = Bret::getExplore();
                echo json_encode($result);
                break;
            case "MOSTSHARED":
                $userId = User::getCurrentUserId();
                $result = Bret::getMostSharedBrets(7);
                echo json_encode($result);
                break;
            case "YOURBRETS":
                $result = Bret::getBrets($userId);
                echo json_encode($result);
                break;
            case "BRET":
                $bretId = $params[2];
                $result = Bret::withId($bretId);
                echo json_encode($result);
                break;
            case "SAVEBRET":
                $data = $_POST['data'];
                $name = $_POST['name'];
                $description = $_POST['description'];
                $user = User::getLogedInUser();
                $alias = str_replace(' ', '-', strtolower($name));
                $bretId = 0;
                if (!isset($params[2]))
                    $params[2] = '';
                if ($params[2] != '') {
                    $bretId = $params[2];
                }
                $db = Database::getInstance();
                if ($bretId == 0) {
                    $query = "INSERT INTO brets (userid, name, description, alias, folderid, data, privacy) VALUES ($user->id,'$name', '$description', '$alias', 1, '$data', 1)";
                    $db->query($query);
                    $query = "SELECT MAX(id) FROM brets WHERE userid = $user->id ORDER BY id DESC";
                    $result = $db->query($query);
                    $bretId = $result->dataTable->rows[0][0];
                } else {
                    $query = "UPDATE brets SET data='$data', name = '$name', description = '$description' WHERE id = $bretId";
                    $db->query($query);
                }
                $images = json_decode($_POST['images']);
                $query = "DELETE FROM images WHERE bretid = $bretId";
                $db->query($query);
                for ($index = 0; $index < count($images) - 1; $index++) {
                    $imgIndex = $index + 1;
                    $base64 = str_replace('data:image/png;base64,', '', $images[$index]);
                    if (strlen($base64) < strlen($images[$index])) {
                        $img = base64_decode($base64);
                        mkdir("Images/brets/$bretId");
                        $file = file_put_contents("Images/brets/$bretId/slide-$imgIndex.png", $img);
                    }
                    $query = "INSERT INTO images (bretid, imageurl, `index`) VALUES ($bretId, 'slide-$imgIndex.png', $imgIndex)";
                    $db->query($query);
                }
                echo $bretId;
                break;
            case "DELETEBRETS":
                $result = Bret::deleteMulti($_POST['ids']);
                echo $result;
                break;
            case "RESTOREBRETS":
                $result = Bret::restoreMulti($_POST['ids']);
                echo $result;
                break;
            case "REGISTER":
                if(isset($_POST['recaptcha_res']) && isset($_POST['profile'])) {
                    //echo reCaptcha::check_recaptcha($_POST['recaptcha_res']);
                    $profile = json_decode($_POST['profile']);
                    $user = (array) $profile;
                    $result = User::addUser($user);
                    echo $result;
                }else {
                    echo "wrong";
                }
                break;
            case "ADDUSER":
                if(isset($_POST['profile'])) {
                    $profile = json_decode($_POST['profile']);
                    $user = (array) $profile;
                    $result = User::addUser($user);
                    echo $result;
                }else {
                    echo "wrong";
                }
                break;
            case "DELETEUSERS":
                $result = User::deleteMulti($_POST['ids']);
                echo $result;
                break;
            case "ENABLEUSERS":
                $result = User::enableMulti($_POST['ids']);
                echo $result;
                break;
            case "DISABLEUSERS":
                $result = User::disableMulti($_POST['ids']);
                echo $result;
                break;
            case "CHANGEPASSWORD":
                echo User::changePassword($_POST['oldpassword'], $_POST['newpassword']);
                break;
            case 'UPDATEPROFILE':
                echo User::updateProfile($_POST['name'], $_POST['phone'], $_POST['company'], $_POST['position']);
                break;
            case "UPLOADAVATAR":
                User::uploadAvatar($_FILES["avatar-image"]);
                break;
            default:
                break;
        }
        return;
    case "SLIDESHOW":
        include "View/Desktop/Master/SlideShow.php";
        return;
    case "SAVEIMAGE":
        $userId = User::getCurrentUserId();
        $bretId = 'tmp/' . $userId;
        $index = 1;
        if (isset($params[2]))
            $bretId = $params[2];
        if (isset($params[1]))
            $index = $params[1];
        echo "Images/brets/$bretId/slide-$index.png";
        if (isset($HTTP_RAW_POST_DATA)) {
            $img = base64_decode(str_replace('data:image/png;base64,', '', $HTTP_RAW_POST_DATA));
            $file = file_put_contents("Images/brets/$bretId/slide-$index.png", $img);
            echo $file ? "succeed" : "failed";
        } else {
            echo "no data";
        }
        return;
        break;
    case "UPLOAD":

        // Output JSON
        function outputJSON($msg, $status = 'error') {
            header('Content-Type: application/json');
            die(json_encode(array(
                'data' => $msg,
                'status' => $status
            )));
        }

        // Check for errors
        if ($_FILES['SelectedFile']['error'] > 0) {
            outputJSON('An error ocurred when uploading.');
        }

        if (!getimagesize($_FILES['SelectedFile']['tmp_name'])) {
            outputJSON('Please ensure you are uploading an image.');
        }

        // Check filetype
        if ($_FILES['SelectedFile']['type'] != 'image/png') {
            outputJSON('Unsupported filetype uploaded.');
        }

        // Check filesize
        if ($_FILES['SelectedFile']['size'] > 500000) {
            outputJSON('File uploaded exceeds maximum upload size.');
        }

        // Check if the file exists
        if (file_exists('upload/' . $_FILES['SelectedFile']['name'])) {
            outputJSON('File with that name already exists.');
        }

        // Upload file
        if (!move_uploaded_file($_FILES['SelectedFile']['tmp_name'], 'upload/' . $_FILES['SelectedFile']['name'])) {
            outputJSON('Error uploading file - check destination is writeable.');
        }

        // Success!
        outputJSON('File uploaded successfully to "' . 'upload/' . $_FILES['SelectedFile']['name'] . '".', 'success');
        return;
        break;
    default:
        header('HTTP/1.0 404 Not Found');
        echo "<style>
		body {background: #f9fee8;margin: 0; padding: 20px; text-align:center; font-family:Arial, Helvetica, sans-serif; font-size:14px; color:#666666;}
		.error_page {width: 600px; padding: 50px; margin: auto;}
		.error_page h1 {margin: 20px 0 0;}
		.error_page p {margin: 10px 0; padding: 0;}		
		a {color: #9caa6d; text-decoration:none;}
		a:hover {color: #9caa6d; text-decoration:underline;}
		</style><body class=\"login\">
  <div class=\"error_page\">
    <img alt=\"Kidmondo_face_sad\" src=\"/Images/kidmondo_face_sad.gif\">
    <h1>We're sorry...</h1>
    <p>The page or journal you are looking for cannot be found.</p>
    <p><a href=\"$host\">Return to the homepage</a></p>
  </div>

</body>";
        exit();
        break;
}

if (!isset($params[1]))
    $params[1] = '';

//Generate View
if (strtoupper($params[0]) !== "LOGIN") {
    $masterView = MasterView::getInstance();
    $masterView->param = $params[0];
    $masterView->pageTitle = $pageTitle;
    $masterView->mainView = "View/" . $deviceType . "/$params[0]/" . $params[0] . "ViewHTML.php";
    $masterView->viewPort = "View/" . $deviceType . "/$params[0]/" . $params[0] . "ViewPortHTML.php";
    if (strtoupper($params[1]) == 'VIEWPORT') {
        $masterView->display("MasterViewPort.php");
    } else if (strtoupper($params[1]) == 'MAINVIEW') {
        $masterView->display("MasterMainView.php");
    } else {
        $masterView->display("MasterPage.php");
    }
}

header('Content-length: ' . ob_get_length());

#region Procedures

function getProd($data) {
    return $data;
}

function login($login) {
    return bpServer::login($login);
}

function saveBret($id, $userid, $name, $description, $alias, $folderid, $data) {
    return bpServer::saveBret($id, $userid, $name, $description, $alias, $folderid, $data);
}

function getBretData($id) {
    return Bret::getBretData($id);
}
